import { execSync } from 'child_process';
import { resolve } from 'path';
import { lstatSync, readFileSync } from 'fs';

// @see https://github.com/return-0x0/node-clear-npx-cache/blob/master/src/index.ts#L6
export const getNpmCacheDir = () => execSync('npm config get cache').toString().trimEnd();
// @see https://github.com/return-0x0/node-clear-npx-cache/blob/master/src/index.ts#L7
export const getNpxCacheDir = () => resolve(getNpmCacheDir(), '_npx');

export function isDir(path: string) {
  try {
    return lstatSync(path).isDirectory();
  } catch (e) {
    //
  }
  return false;
}

export function isFile(path: string) {
  try {
    return lstatSync(path).isFile();
  } catch (e) {
    //
  }
  return false;
}

export function readJson<T>(path: string): T | undefined {
  try {
    const buf = readFileSync(path);
    return JSON.parse(buf.toString()) as T;
  } catch (e) {
    return undefined;
  }
}

export function extractErrorMessage(err: unknown) {
  if (err == null)
    return '';
  if (err instanceof Error) {
    return err.message;
  } else if (typeof err === 'string') {
    return err;
  }
  return '未知的错误';
}
